﻿$(document).ready(Page_Load);

function Page_Load(e) {
    // convert all buttons to jQuery UI buttons.
    $("button").button();
    $('[name="btnAccount"]').button();

    $('input').focus(function () {
        $(this).removeClass("ui-state-error");
    });

    $('[name="btnLogin"]').click(function () {
        $("#dialog-login").dialog({
            resizable: false,
            height: 325,
            width: 350,
            modal: true,
            buttons: {
                'Login': function () {
                    ValidateLogin();
                },
                'Forgot Password': function () {
                    location.href = "/Process/PasswordRecovery.aspx";
                }
            },
            close: function () {
                $("#login-user").val("");
                $("#login-password").val("");

                $("#error-container").removeClass("ui-state-error ui-corner-all");
                $("#error").html("");

                $('input').removeClass("ui-state-error");
            }
        });
    });

    $('[name="btnNewUser"]').click(function () {
        $("#dialog-newuser").dialog({
            resizable: false,
            height: 455,
            width: 450,
            modal: true,
            buttons: {
                'Create User': function () {
                    ValidateNewUser();
                },
                'Close': function () {
                    $(this).dialog('close');
                }
            },
            close: function () {
                $("#new-user").val("");
                $("#new-email").val("");
                $("#new-password1").val("");
                $("#new-password2").val("");
                $("#new-question").val("");
                $("#new-answer").val("");
                
                $(".error-container").removeClass("ui-state-error ui-corner-all");
                $(".error").html("");

                $('input').removeClass("ui-state-error");
            }
        });
    });

    if (typeof approved != "undefined") {

        if (approved == "true") {
            approved = null;
            var $dialog = $('<div></div>')
		        .html('Congratulations! Your account has been verified.  Please log in to begin using the application.')
		        .dialog({
		            autoOpen: false,
		            resizable: false,
		            height: 325,
		            width: 350,
		            modal: true,
		            buttons: {
		                'Close': function () {
		                    $(this).dialog('close');
		                }
		            },
		            title: 'User Verified'
		        });
            $dialog.dialog('open');
        }
    }

    LoadProjectQuickLaunch();

    if (displayissuelink == "True") {
        var $dialog = $('#issuelink')
		.html('<a href="http://code.google.com/p/my-tr-web-project/issues/list" title="Submit Bug Report" target="_blank">Submit Bug</a>')
        .makeFloat({ x: 0, y: 0, speed: "veryfast" });

        $('#issuelink a').button();
        $('#issuelink a').addClass("ui-state-error ui-corner-all");
    }
}



function ValidateNewUser() {
    var username = $("#new-user"),
			email = $("#new-email"),
            email2 = $("#new-email2"),
			password1 = $("#new-password1"),
            password2 = $("#new-password2"),
            question = $("#new-question"),
            answer = $("#new-answer"),
			allFields = $([]).add(username).add(email).add(password1).add(password2).add(question).add(answer);

    var bValid = true;

    bValid = bValid && checkLength(username, "username", 5);
    bValid = bValid && checkLength(email, "email", 6);
    bValid = bValid && checkPasswords(password1, password2, "Passwords");
    bValid = bValid && checkPasswords(email, email2, "Emails");

    bValid = bValid && checkRegexp(password1, /^.*(?=.{7,})(?=.*[a-z])(?=.*[A-Z])(?=.*[\d\W]).*$/, "Password length must be greated than 7 and contain at least 1 lowercase, 1 uppercase, 1 number and 1 special character.");
    bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Enter a valid email address.  eg. user@email.com");

    bValid = bValid && checkLength(question, "security question", 3);
    bValid = bValid && checkLength(answer, "security answer", 3);

    if (bValid) {
        var webMethodParams = JSON.stringify({ UserName: username.val(), Password: password1.val(), Email: email.val(), Question: question.val(), Answer: answer.val() });

        $.ajax(
        {
            type: "POST",
            async: true,
            url: "Default.aspx/ValidateNewUser",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: webMethodParams,
            success: ValidateNewUser_Success,
            error: ValidateNewUser_Error
        });
    
    }
}

function ValidateNewUser_Success(data, textStatus, XMLHttpRequest) {
    var result = data.d;
    switch (result) {
        case "Success":
            $("#dialog-newuser").dialog('close');
            var $dialog = $('<div></div>')
		        .html('The new user is currently disabled, you will recieve an email shortly to verify your email address and with instructions on enabling your new account.  Please check your junk mail folder.')
		        .dialog({
		            autoOpen: false,
		            resizable: false,
		            height: 325,
		            width: 350,
		            modal: true,
		            buttons: {
		                'Close': function () {
		                    $(this).dialog('close');
		                }
		            },
		            title: 'New User Created Successfully'
		        });
            $dialog.dialog('open');
            break;
        default:
            updateErrors(GetStatusMessage(result));
            break;
    }
}

function ValidateNewUser_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "ValidateNewUser", 100);
    alert("An error occurred validating the login. Error: " + XMLHttpRequest);

}


function ValidateLogin() {
    var username = $("#login-user").val();
    var password = $("#login-password").val();

    var webMethodParams = JSON.stringify({ UserName: username, Password: password });

    $.ajax(
    {
        type: "POST",
        async: true,
        url: "Default.aspx/ValidateLogin",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: webMethodParams,
        success: ValidateLogin_Success,
        error: ValidateLogin_Error
    });

}

function ValidateLogin_Success(data, textStatus, XMLHttpRequest) {
    var result = data.d;

    if (result) {
        $("#loginform").submit();
    } else {
        $(".error-container").addClass("ui-state-error ui-corner-all");
        updateErrors("Login information is incorrect.");
    }
}

function ValidateLogin_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "ValidateLogin", 100);
    alert("An error occurred validating the login. Error: " + XMLHttpRequest);

}

function Log(message, category, priority) {
    var webMethodParams = JSON.stringify({ Message: message, Category: category, Priority: priority });

    $.ajax(
    {
        type: "POST",
        async: true,
        url: "Default.aspx/Log",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: webMethodParams,
        success: Log_Success,
        error: Log_Error
    });

}

function Log_Success(data, textStatus, XMLHttpRequest) {
}

function Log_Error(XMLHttpRequest, textStatus, errorThrown) {
}

function GetStatusMessage(value) {
    switch (value) {
        case "InvalidUserName":
            return ("The user name was not found in the database.");
            break;
        case "InvalidPassword":
            return ("The password is not formatted correctly.");
            break;
        case "InvalidQuestion":
            return ("The password question is not formatted correctly.");
            break;
        case "InvalidAnswer":
            return ("The password answer is not formatted correctly.");
            break;
        case "InvalidEmail":
            return ("The e-mail address is not formatted correctly.");
            break;
        case "DuplicateUserName":
            return ("The user name already exists.");
            break;
        case "DuplicateEmail":
            return ("The e-mail address already exists.");
            break;
        default:
            return ("The unknown error has occured while attempting to validate the information.");
            break;
    }

}

function LoadProjectQuickLaunch() {
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "/Authenticated/Projects/Projects.aspx/GetUsersProjects",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: LoadQuickProjects_Success,
                error: LoadQuickProjects_Error
            });
}

function LoadQuickProjects_Success(data, textStatus, XMLHttpRequest) {
    var projectsdata = data.d;

    if (projectsdata.length > 0) {
        var options = $("<select id='ddlQuickProjects'></select>");
        options.children().remove();
        options.append("<option />");

        $.each(projectsdata, function (i, item) {
            if (item["ActiveInd"] == "True") {
                options.append($("<option />").val(item["ProjectId"]).text(item["Name"]));
            }
        });

        $("#QuickLaunchProjects").css("display", "inline");

        if ($("#ddlQuickProjects") != null) {
            $("#ddlQuickProjects").remove();
        }

        $("#QuickLaunchProjects").append(options);

        $("#ddlQuickProjects").change(function () {
            location.href = "/Authenticated/Projects/Project.aspx?id=" + $(this).val();
        });
    }
    else {
        $("#QuickLaunchProjects").css("display", "none");
    }
}

function LoadQuickProjects_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadProjects", 100);
    $("#QuickLaunchProjects").css("display", "none");
}